/*
 *  author: Honrun
 */
#include "stm32f4xx_hal.h"
#include "DevicesSPI.h"


SPI_HandleTypeDef g_SPI2Handle;


void vSPI2Init(void)
{
    GPIO_InitTypeDef  GPIO_InitStruct = {0};

    /* Enable GPIO TX/RX clock */
    __HAL_RCC_GPIOB_CLK_ENABLE();

    /* Enable SPI peripheral Clock */
    __HAL_RCC_SPI2_CLK_ENABLE();


    GPIO_InitStruct.Mode      = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull      = GPIO_NOPULL;
    GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Pin       = GPIO_PIN_12;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /* SPI SCK GPIO pin configuration  */
    GPIO_InitStruct.Pin       = GPIO_PIN_13;
    GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull      = GPIO_PULLDOWN;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    /* SPI MISO GPIO pin configuration  */
    GPIO_InitStruct.Pull      = GPIO_PULLUP;
    GPIO_InitStruct.Pin       = GPIO_PIN_14 | GPIO_PIN_15;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    SPI2_NSS_DISABLE();


    /* Set the SPI parameters */
    g_SPI2Handle.Instance               = SPI2;
    g_SPI2Handle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
    g_SPI2Handle.Init.Direction         = SPI_DIRECTION_2LINES;
    g_SPI2Handle.Init.CLKPhase          = SPI_PHASE_1EDGE;
    g_SPI2Handle.Init.CLKPolarity       = SPI_POLARITY_LOW;
    g_SPI2Handle.Init.CRCCalculation    = SPI_CRCCALCULATION_DISABLE;
    g_SPI2Handle.Init.CRCPolynomial     = 7;
    g_SPI2Handle.Init.DataSize          = SPI_DATASIZE_8BIT;
    g_SPI2Handle.Init.FirstBit          = SPI_FIRSTBIT_MSB;
    g_SPI2Handle.Init.NSS               = SPI_NSS_SOFT;
    g_SPI2Handle.Init.TIMode            = SPI_TIMODE_DISABLE;
    g_SPI2Handle.Init.Mode              = SPI_MODE_MASTER;
    HAL_SPI_Init(&g_SPI2Handle);

    __HAL_SPI_ENABLE(&g_SPI2Handle);
}

int8_t cSPIWriteDatas(SPI_HandleTypeDef *hSPIHand, uint8_t *pBuffer, int32_t iLength)
{
    int8_t cError = 0;

    if(HAL_SPI_Transmit(hSPIHand, pBuffer, iLength, 5000) != HAL_OK)
        cError = -1;

    return cError;
}

int8_t cSPIWriteByte(SPI_HandleTypeDef *hSPIHand, uint8_t ucByte)
{
    int8_t cError = 0;

    if(HAL_SPI_Transmit(hSPIHand, &ucByte, 1, 5000) != HAL_OK)
        cError = -1;

    return cError;
}

int8_t cSPIReadDatas(SPI_HandleTypeDef *hSPIHand, uint8_t *pBuffer, int32_t iLength)
{
    int8_t cError = 0;

    if(HAL_SPI_Receive(hSPIHand, pBuffer, iLength, 5000) != HAL_OK)
        cError = -1;

    return cError;
}

int8_t cSPIReadByte(SPI_HandleTypeDef *hSPIHand, uint8_t *pucByte)
{
    int8_t cError = 0;

    if(HAL_SPI_Receive(hSPIHand, pucByte, 1, 5000) != HAL_OK)
        cError = -1;

    return cError;
}
